<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>采购指令明细</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
		.table td {
			vertical-align: middle;
		}
		.footer {
			position:fixed; bottom:0; background:#ABABAB; width:100%; height:35px; line-height:32px; z-index:9999; opacity:1;
			filter:alpha(opacity=60); _bottom:auto; _width:100%; _position:absolute;text-align: right;
			_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-
			(parseInt(this.currentStyle.marginTop, 10)||0)-(parseInt(this.currentStyle.marginBottom, 10)||0)));
	    }
	</style>
	<script type="text/javascript">
		$(document).ready(function() {
			var nodeLen = $(".jbox-button-panel", top.document).length;
			$(".jbox-button-panel", top.document).eq(nodeLen-1).remove();
			if('${type}' != ''){
				parent.mainFrame.location.reload();
			}
		});
		//查看采购指令该商品对应的采购记录
        function showInventoryDetail(url){
        	top.$.jBox.defaults.top="8%";
        	top.$.jBox.open("iframe:"+url, "入库记录",$(top.document).width()-500,$(top.document).height()-100,{
				buttons:{"确定":true}, loaded:function(h){
					$(".jbox-content", top.document).css("overflow-y","hidden");
				}
			});
        }
        function deletePurchaseDetail(id){
        	top.$.jBox.confirm("确认删除该清单？",'系统提示',function(v,h,f){
				if(v=='ok'){
					loading("正在提交，请稍等...");
					var param = "id="+id;
					$.ajax({
						type: 'post',
						url: '${ctx }/ivm/purchase/deletePurchaseDetail',
						data: param,
						dataType: 'json',
						success: function(data){
							if(data.status==200){
								showJBoxMess(data.message,"success");
								$("#inputForm").submit();
							}else{
								showJBoxMess(data.message,"error");
							}
						},
						failure: function(){
							showJBoxMess("操作失败","error");
						}
					});
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
		}
		
		function updatePurchaseDetailState(id){
			top.$.jBox.confirm("确定完成该商品采购？",'系统提示',function(v,h,f){
				if(v=='ok'){
					loading("正在提交，请稍等...");
					var param = "id="+id+"&state=1";
					$.ajax({
						type: 'post',
						url: '${ctx }/ivm/purchase/updatePurchaseDetailState',
						data: param,
						dataType: 'json',
						success: function(data){
							if(data.status==200){
								showJBoxMess(data.message,"success");
								$("#inputForm").submit();
							}else{
								showJBoxMess(data.message,"error");
							}
						},
						failure: function(){
							showJBoxMess("操作失败","error");
						}
					});
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
		}
		
        //检测商品编号
        function checkProductCode(){
        	var obj = $("#code");
        	if($("#code").val()==""){
				showJBoxMess("请输入商品编号或名称.","error");
				return;
			}
			if($(obj).val()!=""){
				//异步保存活动
				$.ajax({
					type: 'post',
					url: '${ctx}/ivm/inventory/checkProductCode',
					data: 'merchantId=${purchase.merchant.id}&code='+$(obj).val(),
					dataType: 'json',
					success: function(data){
						if(data.status==200){
							var product = data.result;
							var isExists = false;
				        	$("input[id='productCode']").each(function(){
				        		if($(this).val()==product.code){
				        			showJBoxMess("商品"+$(obj).val()+"已存在，请重新输入！","error");
				        			isExists=true;
				        			return false;
				        		}
				        	});
				        	if(isExists) return;
							createHmPurchaseDetail();
						}else{
							showJBoxMess(data.message,"error");
						}
					},
					failure: function(){
						showJBoxMess("操作失败","error");
					}				
				});
			}
		}
		function createHmPurchaseDetail(){
			//异步手动生成商品采购清单
			$.ajax({
				type: 'get',
				url: '${ctx}/ivm/purchase/createHmPurchase',
				data: 'merchantId=${purchase.merchant.id}&code='+$("#code").val(),
				dataType: 'json',
				success: function(data){
					if(data.status==200){
						//获取商品最大的序号
						var num = $(".detail").length;
						var detail = data.result;
						var html = '<tr class="editTr">';
						html += '<td class="detail">'+(num+1)+'</td>'
						html += '<td>';
						html += '<input type="hidden" id="detailId" name="detailId" value="" />';
						html += '<input type="hidden" id="type" name="type" value="2" />';
						html += '<input type="hidden" id="orderId" name="orderId" value="" />';
						html += '<input type="hidden" id="productId" name="productId" value="'+detail.product.id+'" />';
						html += '<input type="hidden" id="productCode" value="'+detail.product.code+'" />';
						html += '<input type="hidden" id="inventoryId" name="inventoryId" value="" />';
						html += detail.product.code;
						html += '</td>';
						html += '<td>'+detail.product.name+'</td>';
						if(detail.product.purchaseDesc==undefined){
							html += '<td></td>';
						}else{
							html += '<td>'+detail.product.purchaseDesc+'</td>';
						}
						html += '<td><input name="purchaseNumber" value="'+detail.purchaseNumber+'" htmlEscape="false" maxlength="20" class="required digits" onchange="updateNum(this, 0)" style="text-align: center;width:60px;"/>'+detail.product.specUnit.name+'</td>';
						html += '<td><input name="adviceNumber" value="'+detail.adviceNumber+'" htmlEscape="false" maxlength="20" min="0" class="" style="text-align: center;width:60px;"/>'+detail.product.specUnit.name+'</td>';
						html += '<td><input name="storageNumber" value="" onchange="changeNum(this)" htmlEscape="false" maxlength="20" min="1" class="" style="text-align: center;width:60px;"/>'+detail.product.specUnit.name+'</td>';
						html += '<td id="rate"></td>';
						html += '<td><input name="totalAmount" value="" onchange="changeAmount(this)" htmlEscape="false" maxlength="20" min="1" class="" style="text-align: center;width:60px;"/></td>';
						html += '<td id="price"></td>';
						html += '<td>手动</td>';
						html += '<td>';
						html += '<a href="javascript:" onclick="removeDetail(this)">删除</a>';
						html += '</td>';
						html += '</tr>';
						$(".detailBody").append(html);
						$(".overBtn").hide();
						$("#code").val("");
					}else{
						showJBoxMess(data.message,"error");
					}
				},
				failure: function(){
					showJBoxMess("操作失败","error");
				}				
			});
		}
		//删除手动添加的商品
      	function removeDetail(obj){
      		top.$.jBox.confirm("确认删除该清单？",'系统提示',function(v,h,f){
				if(v=='ok'){
					$(obj).parent().parent().remove();
					//判断是否存在可编辑的行
					if($(".editTr").length>0){
						$(".overBtn").hide();
					}
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
      	}
      	function savePurchaseDetail(){
      		var detailList = "";
			var isOK = true;
			//新添加的商品
			$(".editTr").each(function(index){
				var detailTr = $(this);
				var id = detailTr.find("input[name='detailId']").val();
				var type = detailTr.find("input[name='type']").val();
				var orderId = detailTr.find("input[name='orderId']").val();
				var productId = detailTr.find("input[name='productId']").val();
				var purchaseNumber = detailTr.find("input[name='purchaseNumber']").val();//计划采购量
				var adviceNumber = detailTr.find("input[name='adviceNumber']").val();//建议采购量
				var storageNumber = detailTr.find("input[name='storageNumber']").val();//采购量
				var totalAmount = detailTr.find("input[name='totalAmount']").val();//采购金额
				var inventoryId = detailTr.find("input[name='inventoryId']").val();//入库记录ID
				var item = id+":"+type+":"+orderId+":"+productId+":"+purchaseNumber+":"+storageNumber+":"+totalAmount+":"+inventoryId+":"+adviceNumber;
				if(purchaseNumber=="0"){
					showJBoxMess("采购数量不能为0","error");
					isOK = false;
					return false;
				}
				detailList+=","+item;
			});
			if(!isOK) return;
			//if(detailList!="") detailList = detailList.substring(1);
			//已有商品
			$(".purchaseTr").each(function(index){
				var detailTr = $(this);
				var id = detailTr.find("input[name='detailId']").val();
				var type = detailTr.find("input[name='type']").val();
				var orderId = detailTr.find("input[name='orderId']").val();
				var productId = detailTr.find("input[name='productId']").val();
				var purchaseNumber = detailTr.find("input[name='purchaseNumber']").val();//计划采购量
				var adviceNumber = detailTr.find("input[name='adviceNumber']").val();//建议采购量
				var storageNumber = detailTr.find("input[name='storageNumber']").val();//采购量
				var totalAmount = detailTr.find("input[name='totalAmount']").val();//采购金额
				var inventoryId = detailTr.find("input[name='inventoryId']").val();//入库记录ID
				var item = id+":"+type+":"+orderId+":"+productId+":"+purchaseNumber+":"+storageNumber+":"+totalAmount+":"+inventoryId+":"+adviceNumber;
				if(purchaseNumber=="0"){
					showJBoxMess("采购数量不能为0","error");
					isOK = false;
					return false;
				}
				detailList+=","+item;
			});
			if(!isOK) return;
			if(detailList!="") detailList = detailList.substring(1);
			
			//开始生成采购指令
			loading("正在提交，请稍等...");
			var param = "purchaseId=${purchase.id}&detailList="+detailList+"&memberId="+$("#memberId").val();
			$.ajax({
				type: 'post',
				url: '${ctx}/ivm/purchase/savePurchaseDetail',
				data: param,
				dataType: 'json',
				success: function(data){
					if(data.status==200){
						showJBoxMess(data.message,"success");
						parent.mainFrame.location.reload();
						$("#inputForm").submit();
					}else{
						showJBoxMess(data.message,"error");
					}
				},
				failure: function(){
					showJBoxMess("操作失败","error");
				}
			});
		}
		//打开商品入库入口
		function openIntoInventory(id){
			top.$.jBox.defaults.top="8%";
			top.$.jBox.open("iframe:${ctx}/ivm/inventory/showIntoInventory?productId="+id+"&purchaseId=${purchase.id}", "商品入库",$(top.document).width()-700,$(top.document).height()-100,{
				buttons:{"确定":false}, loaded:function(h){
					$(".jbox-content", top.document).css("overflow-y","hidden");
				}
			});
		}
		//导出采购指令明细数据
       function exportPurchaseDetail(){
       		top.$.jBox.defaults.top="27%";
       		var href="${ctx}/ivm/purchase/export?id=${purchase.id }";
			top.$.jBox.confirm("确认要导出采购指令明细数据吗？","系统提示",function(v,h,f){
				if(v=="ok"){
					$("#searchForm").attr("action",href);
					$("#searchForm").submit();
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
		}
		function previewPurchaseDetail(){
			top.$.jBox.defaults.top="8%";
        	top.$.jBox.open("iframe:${ctx}/ivm/purchase/previewPurchaseDetail?id=${purchase.id}", "采购指令明细—预览",$(top.document).width()-500,$(top.document).height()-100,{
				buttons:{"确定":true}, loaded:function(h){
					$(".jbox-content", top.document).css("overflow-y","hidden");
				}
			});
		}
		//修改采购数量，重新计算采购偏差比，单价
		function changeNum(obj){
			var playNum = $(obj).parent().parent().find("input[name='purchaseNumber']").val();//计划采购数量
			var purchaseNum = $(obj).val();//实际采购数量
			var rate = accDiv(accSub(playNum,purchaseNum)*100,playNum);
			$(obj).parent().parent().find("td[id='rate']").text(rate+"%");
			var amount = $(obj).parent().parent().find("input[name='totalAmount']").val();//采购金额
			var price = accDiv(amount,purchaseNum);//单价
			$(obj).parent().parent().find("td[id='price']").text(price);
		}
		//修改采购金额，重新计算单价
		function changeAmount(obj){
			var purchaseNum = $(obj).parent().parent().find("input[name='storageNumber']").val();//实际采购数量
			var amount = $(obj).val();//采购金额
			var price = accDiv(amount,purchaseNum);
			$(obj).parent().parent().find("td[id='price']").text(price);
		}
		//完成采购
		function finfishPurchase(id){
			top.$.jBox.defaults.top="27%";
			var href="${ctx}/ivm/purchase/updateState?id="+id+"&state=1"
			top.$.jBox.confirm("确定完成该采购指令吗？","系统提示",function(v,h,f){
				if(v=="ok"){
					savePurchaseDetail();
					$("#searchForm").attr("action",href);
					$("#searchForm").submit();
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
		}
	</script>
</head>
<body>
<form:form id="searchForm" action="${ctx}/ivm/purchase/export?id=${purchase.id }" method="post">
	<tags:message content="${message}"/>
</form:form>
<form:form id="inputForm" action="${ctx}/ivm/purchase/showPurchaseDetail?id=${purchase.id }" method="post">
	<div style="margin:10px;margin-bottom: 50px;">
		<fieldset class="fieldset">
			<div>
				编号：${purchase.code }<br>
				采购员：${purchase.member.name }<br>
				手机号：${purchase.member.phone }<br>
				生成日期：${purchase.createDate }<br>
			</div>
		</fieldset>
		<table id="contentTable" class="table table-striped table-bordered table-condensed">
			<thead>
				<tr>
					<th>序号</th>
					<th>商品编号</th>
					<th>商品名称</th>
					<th>采购说明</th>
					<th>计划采购量</th>
					<th>建议采购量</th>
					<th>实际采购量</th>
					<th>采购偏差比</th>
					<th>采购金额(元)</th>
					<th>单价(元)</th>
					<th>来源</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody class="detailBody">
			<c:forEach items="${purchase.detailList}" var="detail" varStatus="vs">
				<tr class="purchaseTr">
					<td class="detail">${vs.index+1 }</td>
					<td>
						<input type="hidden" id="detailId" name="detailId" value="${detail.id }" />
						<input type="hidden" id="type" name="type" value="${detail.type }" />
						<input type="hidden" id="orderId" name="orderId" value="${detail.order.id }" />
						<input type="hidden" id="productId" name="productId" value="${detail.product.id }" />
						<input type="hidden" id="productCode" value="${detail.product.code }" />
						<input type="hidden" id="purchaseNumber" name="purchaseNumber" value="${detail.purchaseNumber }" />
						<input type="hidden" id="inventoryId" name="inventoryId" value="${detail.inventoryId }" />
						${detail.product.code }
					</td>
					<td>${detail.product.name }</td>
					<td>${detail.product.purchaseDesc }</td>
					<td>${detail.purchaseNumber }${detail.product.specUnit.name }</td>
					<td><input name="adviceNumber" value="${detail.adviceNumber }" htmlEscape="false" maxlength="20" min="0" class="" style="text-align: center;width:60px;"/>${detail.product.specUnit.name }</td>
					<td><input name="storageNumber" value="${detail.storageNumber }" onchange="changeNum(this)" htmlEscape="false" maxlength="20" min="1" class="" style="text-align: center;width:60px;"/>${detail.product.specUnit.name }</td>
					<td id="rate"><fmt:formatNumber value="${(detail.purchaseNumber-detail.storageNumber)*100/detail.purchaseNumber }" pattern="#.##" minFractionDigits="2" />%</td>
					<td><input name="totalAmount" value="${detail.totalAmount }" onchange="changeAmount(this)" htmlEscape="false" maxlength="20" min="1" class="" style="text-align: center;width:60px;"/></td>
					<td id="price"><c:if test="${detail.storageNumber != 0}"><fmt:formatNumber value="${detail.totalAmount/detail.storageNumber }" pattern="#.##" minFractionDigits="2" /></c:if></td>
					<td>${detail.type==1?'订单':'手动' }</td>
					<!-- 
					<td style="text-align: center;">
						<c:if test="${detail.state=='0'}">采购中	</c:if>
						<c:if test="${detail.state=='1'}">已完成	</c:if>
					</td>
					 -->
					<td>
					<c:if test="${detail.state==0}">
						<!-- 
						<a href="#" onclick="openIntoInventory('${detail.product.id}')">入库</a>
						<a href="javascript:" onclick="showInventoryDetail('${ctx }/ivm/inventory/showInventoryDetail?product.id=${detail.product.id}')">入库记录</a>
						<a href="javascript:" onclick="updatePurchaseDetailState('${detail.id}')">完成</a>
						<c:if test="${detail.storageNumber==0 && detail.delFlag!=1 && detail.state!=1}">
						</c:if>
						 -->
						<a href="javascript:" onclick="deletePurchaseDetail('${detail.id}')">删除</a>	
					</c:if>
					</td>
				</tr>
			</c:forEach>
			</tbody>
		</table>
		<c:if test="${purchase.state!=1}">
			<!-- 派送员信息 -->
			<ul class="wl-tab-nav">
				<li><span>分配采购员</span></li>
			</ul>
			<div class="delivery_info">
				<label>采购员:</label>
				<select id="memberId" class="required input-small">
					<option value="">请选择</option>
					<c:forEach  items="${fns:getDeliveryMemberList(2)}" var="item">
						<c:if test="${purchase.member.id==item.id}">
							<option value="${item.id }" selected="selected">${item.name }</option>
						</c:if>
						<c:if test="${purchase.member.id!=item.id}">
							<option value="${item.id }">${item.name }</option>
						</c:if>
					</c:forEach>
				</select>
			</div>
		</c:if>
	</div>
</form:form>
<!--endprint-->
<div class="footer" id="printDiv">
	<c:if test="${purchase.state!='1'}">
		<input type="text" id="code" name="code" htmlEscape="false" maxlength="200" class="required input-small" style="margin-bottom: 0px; width: 180px;" placeholder="请输入商品编号或名称"/>
		<input class="btn btn-primary" type="button" onclick="checkProductCode()" value="添加商品采购"/>
		<input value="保存" type="button" class="btn btn-primary saveBtn" style="margin-right: 5px;" onclick="savePurchaseDetail()"/>
	</c:if>
	<input value="导出" type="button" class="btn btn-primary" style="margin-right: 5px;" onclick="exportPurchaseDetail()"/>
	<input value="预览" type="button" class="btn btn-primary" style="margin-right: 5px;" onclick="previewPurchaseDetail()"/>
	<c:if test="${purchase.state!='1'}">
		<input value="完成" type="button" class="btn btn-primary overBtn" style="margin-right: 5px;" onclick="finfishPurchase('${purchase.id}')"/>
	</c:if>
	<!-- <input value="关闭" type="button" class="btn btn-primary" style="margin-right: 20px;" onclick="top.$.jBox.close();"/> -->
</div>
</body>
</html>